package com.haha.onebot.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haha.onebot.constant.ActionType;
import com.haha.onebot.constant.Constants;
import com.haha.onebot.entity.Bot;
import com.haha.onebot.entity.BotMessage;
import com.haha.onebot.entity.Message;
import com.haha.onebot.entity.OneBotMessage;
import com.haha.onebot.entity.ReplyMessage;
import com.haha.onebot.enums.MessageTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Log4j2
@Component
public class MessageEventListener {

    @Resource
    private Bot bot;

    @Resource
    private ObjectMapper objectMapper;



    @Async
    @EventListener(classes = BotMessage.class, condition = "#botMessage.id == 'message'")
    public void handlerResult(BotMessage botMessage){

        OneBotMessage oneBotMessage = botMessage.getOneBotMessage();

        String messageType = oneBotMessage.getMessageType();

        Boolean ifGroupMessage = false;

        if (messageType != null && messageType.equals(MessageTypeEnum.GROUP.getMessageType())) {
            ifGroupMessage = true;
        }
        List<Message> message = new ArrayList<>();
        if (oneBotMessage.getMessage() instanceof List<?>) {
            try {
                message = objectMapper.readValue(
                        objectMapper.writeValueAsString(
                                oneBotMessage.getMessage()), new TypeReference<List<Message>>() {
                        });
            } catch (JsonProcessingException e) {
                log.error("消息解析失败：{}", e);
            }
        }

        AtomicReference<Long> atQQ = new AtomicReference<>(0L);
        AtomicReference<String> messageText = new AtomicReference<>("");

        AtomicReference<String> replyId = new AtomicReference<>("");

        String echo = "";

        String replyEcho = oneBotMessage.getEcho();

        message.parallelStream().forEach(m -> {
            if (m.getType().equals("at")) {
                atQQ.set(m.getData().getQq());
            } else if (m.getType().equals("text")) {
                messageText.set(m.getData().getText());
            } else if (m.getType().equals("face")) {
                log.info("表情消息");
            } else if (m.getType().equals("reply")) {
                replyId.set(m.getData().getId());
            } else if (m.getType().equals("image")) {
                log.info("图片消息");
            } else {
                log.info("未知消息类型：{}", m.getType());
            }
        });

        Boolean ifAtBot = atQQ.get().equals(oneBotMessage.getSelfId());

        String content = messageText.get().trim();

        if (ifAtBot) {
            log.info("@了机器人");
        } else {
            log.info("消息跟机器人无关");
        }

        String replyContent = "";
        Long userId = oneBotMessage.getUserId();

        //官方机器人
        //q群管家 2854196310L
        if(userId == null || userId.equals(3889047445L) || userId.equals(2854196310L)) {
            return;
        }

        Boolean image = false;
        Boolean video = false;
        Boolean audio = false;

        Long groupId = oneBotMessage.getGroupId();
        if (content.equals("帮助")) {
            replyContent = """
                    你猜我有什么功能！？？？
                    """;
        } else if (content.startsWith("签到")) {
            replyContent = "签你妹的签，滚！！！";
        }

        //拼接消息内容
        try {
            if (replyContent.equals("") && content.equals("") && ifAtBot) {
                replyContent = """
                        干嘛啊 ~~~ [CQ:face,id=178]
                        """; //默认回复
            }

            if (!replyContent.equals("")) {

                if (!image && !video && ifGroupMessage) {
                    String cqCode = "\n [CQ:at,qq=" + userId + "] ";
                    replyContent = replyContent + cqCode;
                }

                ReplyMessage replyMessage = new ReplyMessage();

                replyMessage.setAction(ActionType.SEND_GROUP_MSG);
                Map<String, Object> params = new HashMap<>();
                if (ifGroupMessage) {
                    params.put("group_id", groupId);
                } else {
                    params.put("user_id", userId);
                }

                params.put("message", replyContent.trim());
                replyMessage.setParams(params);

                if (!echo.isBlank()) {
                    replyMessage.setEcho(echo);
                }

                String reply = objectMapper.writeValueAsString(replyMessage);

                bot.getSession().sendMessage(new TextMessage(reply));

            }

        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

}
